<template>
    <div class="cu-modal" :class="{ show: showAuth }" @click="closeAuthModal">
        <div class="cu-dialog" style="width: 900px;" @click.stop>
            <el-row>
                <el-col :span="12">
                    <el-image :src="loginBgUrl"></el-image>
                </el-col>
                <el-col :span="12">
                    <div class="p-30" style="height: calc(500px - 60px)">
                        <div class="text-center mb-30">
                            <el-avatar :size="120" :src="circleUrl"></el-avatar>
                        </div>
                        <template v-if="authType === 'login'">
                            <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
                                <el-form-item prop="account">
                                    <el-input v-model="loginForm.account" placeholder="请输入账号"
                                        prefix-icon="el-icon-user"></el-input>
                                </el-form-item>
                                <el-form-item prop="password" class="mb-15">
                                    <el-input v-model="loginForm.password" placeholder="请输入密码"
                                        prefix-icon="el-icon-lock"></el-input>
                                </el-form-item>
                                <div class="mb-10 text-right">
                                    <el-link :underline="false" @click="showAuthModal('register')">注册账号<i
                                            class="el-icon-arrow-right"></i></el-link>
                                </div>
                                <el-form-item>
                                    <el-button type="warning" style="width: 100%;"
                                        @click="submitForm('loginForm')">登录</el-button>
                                </el-form-item>
                            </el-form>
                        </template>
                        <template v-if="authType === 'register'">
                            <el-form :model="registerForm" :rules="registerRules" ref="registerForm">
                                <el-form-item prop="mobile">
                                    <el-input v-model="registerForm.mobile" placeholder="请输入手机号"
                                        @input="mobileInput($event, 'mobile')" prefix-icon="el-icon-user"></el-input>
                                </el-form-item>
                                <el-form-item prop="code">
                                    <el-input v-model="registerForm.code" placeholder="请输入验证码"
                                        prefix-icon="el-icon-user">
                                        <template #suffix>
                                            <el-button type="text" class="code-btn code-btn-start"
                                                :disabled="!registerForm.isMobileEnd"
                                                :class="{ 'code-btn-end': registerForm.isMobileEnd }"
                                                @click="getSmsCode">{{ codeText }}</el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                                <el-form-item prop="password" class="mb-15">
                                    <el-input v-model="registerForm.password" placeholder="请输入密码"
                                        prefix-icon="el-icon-lock"></el-input>
                                </el-form-item>
                                <div class="mb-10 text-left">
                                    <el-link :underline="false" @click="showAuthModal('login')">
                                        <i class="el-icon-arrow-left"></i>返回登录
                                    </el-link>
                                </div>
                                <el-form-item>
                                    <el-button type="warning" style="width: 100%;"
                                    :disabled="!registerForm.isMobileEnd"
                                        @click="submitForm('registerForm')">注册</el-button>
                                </el-form-item>
                            </el-form>
                        </template>
                        <!-- 协议 -->
                        <div v-if="['login', 'register'].includes(authType)" class="agreement-box">
                            <el-checkbox v-model="protocol">
                                <div class="agreement-text tcp-text flex align-items">
                                    我已阅读并遵守
                                    <div class="tcp-text flex align-items">
                                        <div
                                            @click.stop="$Router.push({ path: '/pages/public/richtext', query: { id: initStore.shop.user_protocol || 0 } })">
                                            《用户协议》</div>
                                        与
                                        <div
                                            @click.stop="$Router.push({ path: '/pages/public/richtext', query: { id: initStore.shop.privacy_protocol || 0 } })">
                                            《隐私协议》</div>
                                    </div>
                                </div>
                            </el-checkbox>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>
/**
 * 登录提示页
 */
import { mapMutations, mapActions, mapState, mapGetters } from 'vuex'
import test from '@/utils/test'
import request from '@/utils/request'
import { login, register } from '@/api/apis'
export default {
    name: 'authModal',
    data () {
        // 验证手机号的规则
        var validateMobile = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('手机号码不能为空'))
            } else if (!test.mobile(value)) {
                callback(new Error('请输入正确的手机号码'))
            } else {
                callback()
            }
        };
        return {
            circleUrl: require('@/assets/img/3ea6beec64369c2642b92c6726f1epng.jpg'),
            loginBgUrl: require('@/assets/img/loginBg.png'),
            codeText: '获取验证码',
            disabledCode: false,
            protocol: false, //是否同意隐私协议
            loginForm: {
                account: '18000000000', // 账号
                password: '111111' // 密码
            },
            loginRules: {
                account: [{
                    required: true,
                    min: 5,
                    message: '请输入账号',
                    trigger: ['change', 'blur']
                }],
                password: [{
                    required: true,
                    message: '请输入密码',
                    trigger: ['change', 'blur']
                },
                /* {
                    pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+\S{5,12}$/,
                    message: '需同时含有字母和数字，长度在6-12之间',
                    trigger: ['change', 'blur']
                } */
                ]
            },
            registerForm: {
                mobile: '18000000000', // 手机号
                code: '1111', // 验证码
                password: '111111', // 密码
                isMobileEnd: false // 手机号输入完毕
            },
            registerRules: {
                code: [{
                    required: true,
                    min: 4,
                    message: '请输入验证码',
                    trigger: ['change', 'blur']
                }],
                mobile: [{
                    required: true,
                    message: '请输入手机号',
                    trigger: ['change', 'blur']
                },
                {
                    validator: validateMobile,
                    trigger: ['change', 'blur']
                }
                ],
                password: [{
                    required: true,
                    message: '请输入密码',
                    trigger: ['change', 'blur']
                }
                ]
            }
        }
    },
    computed: {
        ...mapGetters(['initStore', 'isLogin', 'authType']),
        showAuth: {
            get () {
                return !!this.authType
            },
            set (value) {
            }
        },
    },
    methods: {
        ...mapActions(['getUserInfo', 'showAuthModal']),
        // 关闭模态框
        closeAuthModal () {
            this.$store.dispatch('showAuthModal', '')
        },
        // 手机号是否输入完毕
        mobileInput (e, key) {
            this.registerForm.isMobileEnd = test.mobile(this.registerForm.mobile)
        },
        // 获取短信验证码
        getSmsCode (type) {
            const that = this
            if (that.registerForm.isMobileEnd && !that.disabledCode) {
                // 获取验证码中...
                request({}).then(res => {
                    if (res.code === 1) {
                        that.codeChange()
                        this.$message('验证码已发送，请注意查收短信')
                    } else {
                        this.$message(res.msg)
                    }
                })
            } else {
                this.$message('请稍后再试')
            }
        },
        // 倒计时
        codeChange () {
            if (this.disabledCode) return
            this.disabledCode = true
            let n = 10
            this.codeText = n + 's'
            const run = setInterval(() => {
                n -= 1
                if (n < 0) {
                    clearInterval(run)
                }
                this.codeText = n + 's'
                if (this.codeText < 0 + 's') {
                    this.disabledCode = false
                    this.codeText = '重新获取'
                }
            }, 1000)
        },
        submitForm (formName) {
            let that = this;
            if (['login', 'register'].includes(this.authType) && !this.protocol) {
                this.$message('请同意用户协议')
                return false
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (formName === 'loginForm') {
                        that.loginSubmit();
                    } else if (formName === 'registerForm') {
                        that.registerSubmit();
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        loginSubmit(){
            let that = this;
            login(
                {
                    account: that.loginForm.account,
                    password: that.loginForm.password
                }
            ).then(res => {
                that.$message({message: res.msg,type: 'success'});
                if (res.code === 1) {
                    that.closeAuthModal();
                    // 调用mutation来更新状态
                    this.$store.commit('token', res.data.userinfo.token);
                    this.$store.commit('isLogin', true);
                    this.$store.commit('userInfo', res.data.userinfo);
                }
            })
        },
        registerSubmit(){
            let that = this;
            register(
                {
                    mobile: that.registerForm.mobile,
                    password: that.registerForm.password,
                    code: that.registerForm.code,
                }
            ).then(res => {
                that.$message({ message: res.msg, type: 'success' });
                if (res.code === 1) {
                    that.closeAuthModal();
                    // 调用mutation来更新状态
                    this.$store.commit('token', res.data.userinfo.token);
                    this.$store.commit('isLogin', true);
                    this.$store.commit('userInfo', res.data.userinfo);
                }
            })
        }
    },
    mounted () {
        // 默认先关闭登录注册弹窗
        this.closeAuthModal()
    },
}
</script>

<style lang="less" scoped>
.code-btn[disabled] {
    background-color: #fff;
}

.code-btn-start {
    border-color: #e9b766;
    font-weight: 400;
    color: #e9b766;
    opacity: 0.5;
}

.code-btn-end {
    opacity: 1 !important;
}

.agreement-box {
    text-align: center;

    .agreement-text {
        color: #999999;

        .tcp-text {
            color: #e9b562;
        }
    }

    /deep/.el-checkbox {
        .el-checkbox__input {
            &.is-checked {
                .el-checkbox__inner {
                    border-color: #e9b766;
                    background-color: #e9b766;
                }
            }

            .el-checkbox__inner {
                &:hover {
                    border-color: #e9b766;
                }
            }
        }
    }
}


.el-image {
    display: block
}
</style>